package cn.yangjunda.util;

import cn.yangjunda.MVCException;
import cn.yangjunda.XMLReaderException;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by juanda on 12/9/17.
 */
public class XMLReader {

    private Configuration configuration = new Configuration();

    private Set<Class<?>> classes;

    /**
     * 读取Bean配置文件
     * @param
     * @return
     */
    private Element element;

    @SuppressWarnings("unchecked")
    public void readXML() {
        Document document = null;
        SAXReader saxReader = new SAXReader();
        try {
            ClassLoader classLoader =
                    Thread.currentThread().getContextClassLoader();
            document = saxReader.read(classLoader.getResourceAsStream("juanda-mvc.xml"));
            Element beans = document.getRootElement();
            if("beans".equals(beans.getName())){
                getBeans(beans);
            }
        } catch (DocumentException e) {
//            log.info("读取配置文件出错....");
        }
    }

    private void getBeans(Element node) {
        if ("context".equals(node.getName())){
            List<Attribute> listAttr=node.attributes();//当前节点的所有属性的list
            for(Attribute attr:listAttr){//遍历当前节点的所有属性
                if("base-package".equals(attr.getName())){
                    configuration.setPackagePath(attr.getValue());
                }else if("autowire-open".equals(attr.getName())){
                    try {
                        configuration.setAutowire(Boolean.valueOf(attr.getValue()));
                    }catch (Exception e){
                        configuration.setAutowire(true);
                    }
                }
            }
        }else if("bean".equals(node.getName())){
            Map<String,Object> map = configuration.getBeans();
            List<Attribute> listAttr= node.attributes();//当前节点的所有属性的list
            String id = node.attributeValue("id");
            if (id == null) {
                throw new XMLReaderException("id 内容不能为空");
            }
            String classPath = node.attributeValue("class");
            if (classPath == null) {
                throw new XMLReaderException("class 内容不能为空");
            }
            Class forName = null;
            try {
                forName = Class.forName(classPath);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Object object = null;
            try {
                object = forName.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            List<Element> sonElements = node.elements();
            for (Element element : sonElements) {
                String name = element.attributeValue("name");

                //私有属性赋值
                Field declaredField = null;
                try {
                    declaredField = forName.getDeclaredField(name);
                    Object o = null;

                    String value = element.attributeValue("value");
                    String ref = element.attributeValue("ref");
                    if (ref != null) {
                        o = configuration.getBean(ref);
                    } else {
                        o = ParseObjectUtil.stringToObject(declaredField.getType(), value);
                    }

                    declaredField.setAccessible(true);
                    declaredField.set(object, o);
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
            configuration.setBean(id, object);
//            for(Attribute attr:listAttr){ //遍历当前节点的所有属性
//                if(".*".equals(attr.getValue().substring(attr.getValue().length()-2))){
//                    classes = ClassTools.getClasses(attr.getValue().substring(0,attr.getValue().length()-2));
//                    for (Class<?> clasz : classes) {
//                        map.put(clasz.getName(),firstLowerName(clasz.getName().substring((clasz.getName().lastIndexOf(".") + 1), clasz.getName().length())));
//                    }
//                    configuration.setBeans(map);
//                }else {
//                    if("id".equals(attr.getName())){
//                        id=attr.getValue();
//                    }else if("class".equals(attr.getName())){
//                        className = attr.getValue();
//                    }
//                    if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(className)){
//                        map.put(className,id);
//                        configuration.setBeans(map);
//                    }
//                }
//            }
        }
        //递归遍历当前节点所有的子节点
        List<Element> listElement=node.elements();//所有一级子节点的list
        for(Element e:listElement){//遍历所有一级子节点
            getBeans(e);//递归
        }
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public Element getElement() {
        return element;
    }

    public void setElement(Element element) {
        this.element = element;
    }

    private String firstLowerName(String name) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
        return  name;
    }
}
